const ExperimentModel = require('../models/experiment.model');
const ApiError = require('../utils/ApiError');

exports.getAllExperiments = async () => {
    console.log('开始处理获取所有实验请求');
    try {
        // 从数据库获取数据
        const experiments = await ExperimentModel.getAll();
        // 转换数据结构以匹配原有JSON格式
        return experiments.map(exp => ({
            id: exp.id,
            title: exp.title,
            description: exp.short_description,
            fullDescription: exp.full_description,
            course: exp.course_category,
            duration: exp.duration,
            imageUrl: exp.image_url,
            objectives: exp.objectives.map(obj => obj.objective),
            resources: exp.resources.map(res => ({
                id: res.id,
                name: res.name,
                type: res.type,
                filePath: res.file_path,
                isPublic: res.is_public
            }))
        }));
    } catch (err) {
        console.error('获取实验数据时出错:', err);
        throw new Error('获取实验数据失败');
    }
};

// 获取单个实验详情（从数据库获取）
exports.getExperimentById_new = async (req, res) => {
    try {
        console.log(`获取实验详情请求 ID: ${req.params.id}`);
        const experimentId = parseInt(req.params.id);
        
        // 从数据库获取数据
        const experiment = await ExperimentModel.getById(experimentId);
        
        if (!experiment) {
            console.warn(`实验未找到 ID: ${req.params.id}`);
            return res.status(404).json({ message: '实验未找到' });
        }
        
        // 转换数据结构以匹配原有JSON格式
        const formattedExperiment = {
            id: experiment.id,
            title: experiment.title,
            description: experiment.short_description,
            fullDescription: experiment.full_description,
            course: experiment.course_category,
            duration: experiment.duration,
            imageUrl: experiment.image_url,
            objectives: experiment.objectives.map(obj => obj.objective),
            resources: experiment.resources.map(res => ({
                id: res.id,
                name: res.name,
                type: res.type,
                filePath: res.file_path,
                isPublic: res.is_public
            }))
        };
        
        console.log(`成功获取实验 ID: ${req.params.id}`);
        res.json(formattedExperiment);
    } catch (err) {
        console.error(`获取实验详情时出错 (ID: ${req.params.id}):`, err);
        res.status(500).json({ message: '服务器内部错误' });
    }
};

exports.getStudentExperimentData = async (studentId) => {    
    // 返回模拟数据（实际项目中应从数据库获取）
    return [
        { experimentId: 1, status: "submitted", deadline: "2025-08-15", progress: 100, grade: 85 },
        { experimentId: 2, status: "in_progress", deadline: "2025-08-31", progress: 50, grade: null }
    ];
};

// 根据资源类型获取Content-Type
function getContentType(resourceType) {
    const typeMap = {
        'pdf': 'application/pdf',
        'code': 'application/octet-stream',
        'doc': 'application/msword',
        'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'zip': 'application/zip',
        'tar': 'application/x-tar',
        'gz': 'application/gzip',
        'notebook': 'application/json'
    };
    
    return typeMap[resourceType] || 'application/octet-stream';
}

// 获取所有实验
exports.getExperiments = async (req, res, next) => {
  try {
    console.log('开始处理获取所有实验请求');
    const experiments = await ExperimentModel.getAll();
    res.json({
      success: true,
      data: experiments
    });
  } catch (err) {
    next(err);
  }
};

// 获取单个实验详情
exports.getExperimentById = async (req, res, next) => {
  try {
    const experiment = await ExperimentModel.getById(req.params.id);
    
    if (!experiment) {
      return next(new ApiError('实验未找到', 404));
    }
    
    res.json({
      success: true,
      data: experiment
    });
  } catch (err) {
    next(err);
  }
};

// 下载实验资源
exports.downloadResource = async (req, res) => {
    try {
        const experimentId = parseInt(req.params.experimentId);
        const resourceId = parseInt(req.params.resourceId);
        console.log(`下载资源请求 实验ID: ${experimentId}, 资源ID: ${resourceId}`);
        
        // 从JSON文件获取数据
        const experiments = await getAllExperiments();
        
        // 查找匹配的实验
        const experiment = experiments.find(exp => exp.id === experimentId);
        
        if (!experiment) {
            console.warn(`实验未找到 ID: ${experimentId}`);
            return res.status(404).json({ message: '实验未找到' });
        }
        
        // 查找匹配的资源
        const resource = experiment.resources.find(res => res.id === resourceId);
        
        if (!resource) {
            console.warn(`资源未找到 实验ID: ${experimentId}, 资源ID: ${resourceId}`);
            return res.status(404).json({ message: '资源未找到' });
        }
        
        // 构建文件路径 - 注意：实际文件需要存放在指定位置
        const filePath = path.join(__dirname, '..', 'uploads', resource.filePath);
        console.log(`尝试访问文件: ${filePath}`);
        
        // 检查文件是否存在
        if (!fs.existsSync(filePath)) {
            console.error(`文件不存在: ${filePath}`);
            return res.status(404).json({ message: '文件不存在' });
        }

        // 设置响应头
        res.setHeader('Content-Disposition', `attachment; filename="${encodeURIComponent(resource.name)}"`);
        res.setHeader('Content-Type', getContentType(resource.type));
        console.log(`开始下载: ${resource.name}`);

        // 创建可读流并传输文件
        const fileStream = fs.createReadStream(filePath);
        fileStream.pipe(res);
        
        // 处理错误
        fileStream.on('error', (err) => {
            console.error(`文件流错误: ${err.message}`);
            if (!res.headersSent) {
                res.status(500).json({ message: '文件传输错误' });
            }
        });
    } catch (err) {
        console.error(`下载资源时出错 (实验ID: ${experimentId}, 资源ID: ${resourceId}):`, err);
        res.status(500).json({ message: '下载资源时出错' });
    }
};


// 创建新实验
exports.createExperiment = async (req, res, next) => {
  try {
    const { title, short_description, full_description, course_category, duration, image_url, objectives, resources } = req.body;
    
    if (!title || !full_description || !course_category || !duration) {
      return next(new ApiError('缺少必要参数', 400));
    }
    
    const newExperiment = await ExperimentModel.create({
      title,
      short_description: short_description || '',
      full_description,
      course_category,
      duration,
      image_url: image_url || '',
      objectives: objectives || [],
      resources: resources || []
    });
    
    res.status(201).json({
      success: true,
      data: newExperiment
    });
  } catch (err) {
    next(err);
  }
};

// 更新实验
exports.updateExperiment = async (req, res, next) => {
  try {
    const { id } = req.params;
    const { title, short_description, full_description, course_category, duration, image_url, objectives, resources } = req.body;
    
    if (!title || !full_description || !course_category || !duration) {
      return next(new ApiError('缺少必要参数', 400));
    }
    
    const updatedExperiment = await ExperimentModel.update(id, {
      title,
      short_description: short_description || '',
      full_description,
      course_category,
      duration,
      image_url: image_url || '',
      objectives: objectives || [],
      resources: resources || []
    });
    
    if (!updatedExperiment) {
      return next(new ApiError('实验未找到', 404));
    }
    
    res.json({
      success: true,
      data: updatedExperiment
    });
  } catch (err) {
    next(err);
  }
};

// 删除实验
exports.deleteExperiment = async (req, res, next) => {
  try {
    const { id } = req.params;
    const deleted = await ExperimentModel.delete(id);
    
    if (!deleted) {
      return next(new ApiError('实验未找到', 404));
    }
    
    res.json({
      success: true,
      message: '实验已删除'
    });
  } catch (err) {
    next(err);
  }
};